/*
 * zxxFile.js 基于HTML5 文件上传的核心脚本 http://www.zhangxinxu.com/wordpress/?p=1923
 * by zhangxinxu 2011-09-12
 */

var UploadFile = {
    fileInput: null, //html file控件
    dragDrop: null, //拖拽敏感区域
    upButton: null, //提交按钮
    url: "", //ajax地址
    fileFilter: [], //过滤后的文件数组
    contentId: null, // 放置 上传进度的容器的ID
    filter: function (files) {		//选择文件组的过滤方法
        return files;
    },
    md5: false,
    onSelect: function () {
    }, //文件选择后
    onDelete: function () {
    }, //文件删除后
    onDragOver: function () {
    }, //文件拖拽到敏感区域时
    onDragLeave: function () {
    }, //文件离开到敏感区域时
    onProgress: function () {
    }, //文件上传进度
    onSuccess: function () {
    }, //文件上传成功时
    onFailure: function () {
    }, //文件上传失败时,
    onComplete: function () {
    }, //文件全部上传完毕时

    /* 开发参数和内置方法分界线 */

    //文件拖放
    funDragHover: function (e) {
        e.stopPropagation();
        e.preventDefault();
        this[e.type === "dragover" ? "onDragOver" : "onDragLeave"].call(e.target);
        return this;
    },
    //获取选择文件，file控件或拖放
    funGetFiles: function (e) {
        // 取消鼠标经过样式
        this.funDragHover(e);

        // 获取文件列表对象
        var files = e.target.files || e.dataTransfer.files;
        //继续添加文件

        this.fileFilter = this.filter(files);
        console.log(this.fileFilter);
        this.funDealFiles();
        return this;
    },
    //选中文件的处理与回调
    funDealFiles: function () {
        for (var i = 0, file; file = this.fileFilter[i]; i++) {
            //增加唯一索引值

            file.uuid = "file" + new Date().getTime() + i;
            file.index = i;
        }

        //执行选择回调
        this.onSelect(this.fileFilter);
//         if(this.md5){
//                this.getMd5(this.fileFilter,0); 
//            }
        return this;
    },
    //删除对应的文件
    funDeleteFile: function (fileDelete) {
        var arrFile = [];
        for (var i = 0, file; file = this.fileFilter[i]; i++) {
            if (file != fileDelete) {
                arrFile.push(file);
            } else {
                this.onDelete(fileDelete);
            }
        }
        this.fileFilter = arrFile;
        return this;
    },
//    getMd5:function(files,index){
//        console.log("file"+index);
//        var file = files[index];
//        var esr = this;
//        var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
//       
//        chunkSize = 2097152,                               // read in chunks of 2MB
//        chunks = Math.ceil(file.size / chunkSize),
//        currentChunk = 0,
//        spark = new SparkMD5.ArrayBuffer(),
//        frOnload = function(e) {
//            console.log("read chunk nr", currentChunk + 1, "of", chunks);
//            spark.append(e.target.result);                 // append array buffer
//            currentChunk++;
//
//            if (currentChunk < chunks) {
//                loadNext();
//            }
//            else {
//                file.md5=spark.end();
//                console.info(index+"=="+(esr.fileFilter.length-1)+"  "+file); // compute hash
//                  console.info(file); // compute hash
//                if(index<(esr.fileFilter.length-1)){
//                     
//                    
//                    esr.getMd5(files,(index+1));                  
//                  
//                }else {
//                    esr.funUploadFile();
//                }
//               
//            }
//        },
//        frOnerror = function () {
//            console.warn('oops, something went wrong.');
//        };
//        function loadNext() {
//            var fileReader = new FileReader();
//            fileReader.onload = frOnload;
//            fileReader.onerror = frOnerror;
//
//            var start = currentChunk * chunkSize,
//            end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
//
//            fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
//        };
//
//        loadNext();
//    },  
    //文件上传
    funUploadFile: function (files) {
        var self = this;
        if (location.host.indexOf("sitepointstatic") >= 0) {
            //非站点服务器上运行
            return;
        }
        if (files) {
            this.fileFilter = files;
        }
        for (var i = 0, file; file = this.fileFilter[i]; i++) {

            (function (file) {
                console.log(file);
                var xhr = new XMLHttpRequest();
                if (xhr.upload) {
                    // 上传中
                    xhr.upload.addEventListener("progress", function (e) {
                        self.onProgress(file, e.loaded, e.total, file.uuid);
                    }, false);

                    // 文件上传成功或是失败
                    xhr.onreadystatechange = function (e) {
                        if (xhr.readyState == 4) {
                            if (xhr.status == 200) {
                                self.onSuccess(file, xhr.responseText);
                                var fileIds = file.patId;
                                self.funDeleteFile(file);
                                if (!self.fileFilter.length) {
                                    //全部完毕
                                    self.onComplete(fileIds);
                                }
                            } else {
                                self.onFailure(file, xhr.responseText);
                            }
                        }
                    };

                    // 开始上传
                    xhr.open("POST", (self.url.indexOf("?") > 0 ? self.url : self.url + "?") + "&fileName=" + file.name + "&type=" + self.checkType(file.type) + "&md5=0", true);
                    xhr.setRequestHeader("Cache-Control", "no-cache");
                    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
                    xhr.send(file);
                }
            })(file);
        }

    },
    checkType: function (type) {

        var video = ["AVI", "MOV", "WMV", "3GP", "MP4", "RMVB"];
        var image = ["BMP", "JPG", "PNG", "GIF"];
        var audio = ["MP3", "WAV"];
        if (type.indexOf("video") > -1) {
            return "video";
        } else if (type.indexOf("image") > -1) {
            return "image";
        } else if (type.indexOf("audio") > -1) {
            return "audio";
        } else {
            return "file";
        }
    },
    init: function () {
        var self = this;

        if (this.dragDrop) {
            this.dragDrop.addEventListener("dragover", function (e) {
                self.funDragHover(e);
            }, false);
            this.dragDrop.addEventListener("dragleave", function (e) {
                self.funDragHover(e);
            }, false);
            this.dragDrop.addEventListener("drop", function (e) {
                self.funGetFiles(e);
            }, false);
        }

        //文件选择控件选择
        if (this.fileInput) {
            if (jQuery.isArray(this.fileInput)) {
              
                for (i in this.fileInput) {
                   this.fileInput[i].addEventListener("change", function (e) {
                        self.funGetFiles(e);
                    }, false);
                }
            } else {

                this.fileInput.addEventListener("change", function (e) {
                    self.funGetFiles(e);
                }, false);
            }
        }

        //上传按钮提交
        if (this.upButton) {
            this.upButton.addEventListener("click", function (e) {
                self.funUploadFile(e);
            }, false);
        }
    }
};
